//
//  ConHomeViewController.m
//  Shengzhuli
//
//  Created by FXGuo on 17/3/16.
//  Copyright © 2017 kamangkeji. All rights reserved.
//

#import "ConHomeViewController.h"
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "SZLAccountHelper.h"
#import "SZLMessageListViewController.h"
#import "HomeNetService.h"
#import "TGSementBarVC.h"
#import "ConClubViewController.h"
#import "ConDynamicViewController.h"
#import "ConYueViewController.h"
#import "ConPickViewController.h"
#import "ConAdderViewController.h"
#import "CoverView.h"
#import "ConQrCodeScannerController.h"
#import "PersonNetWork.h"
#import "ShareTool.h"
#import "MBProgressHUD+MJ.h"
#import "ConNearAcInfoViewController.h"
#import "ConOldActivityDetailController.h"

#define KBannerH 550*Scale
@interface ConHomeViewController ()<BMKLocationServiceDelegate>

@property (nonatomic,weak) UIView *naviBackView;//导航条背景
@property (nonatomic,weak) UIButton *messageBtn;
@property (nonatomic,strong) BMKLocationService *locService;
@property (nonatomic,strong) TGSementBarVC *segmentBarVC;

@end

@implementation ConHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20],NSForegroundColorAttributeName:[UIColor whiteColor]};
    self.navigationItem.title = @"玩转地球";
    [self setNav];
    [self setUpView];
    [self setLocation];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollChanged) name:@"KChangeToAdderSelect" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushJump:) name:KPushNotification object:nil];
}
- (void)scrollChanged
{
    self.segmentBarVC.segmentBar.selectedIndex = 4;
}
//推送的跳转
- (void)pushJump:(NSNotification *)noti {
    NSDictionary *userInfo = noti.userInfo;
    if ([userInfo[@"type"] integerValue] == 1) {
        ConNearAcInfoViewController *infoVc = [[ConNearAcInfoViewController alloc]init];
        infoVc.ID = [userInfo[@"id"] integerValue];
        [self.navigationController pushViewController:infoVc animated:YES];
    }else if ([userInfo[@"type"] integerValue] == 2) {
        ConOldActivityDetailController *detailVc = [[ConOldActivityDetailController alloc]init];
        detailVc.ID = [userInfo[@"id"] integerValue];
        [self.navigationController pushViewController:detailVc animated:YES];
    }else if ([userInfo[@"type"] integerValue] == 3) {
        SZLMessageListViewController *messageVc = [[SZLMessageListViewController alloc]init];
        [self .navigationController pushViewController:messageVc animated:YES];
    }
}
- (void)setUpView
{
    self.segmentBarVC.segmentBar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 35);
    //设置segmentBarVC大小
    self.segmentBarVC.view.frame = self.view.bounds;
    [self addChildViewController:self.segmentBarVC];
    [self.view addSubview:self.segmentBarVC.view];
    
    NSArray *items = @[@"俱乐部",@"动态",@"约吗",@"捡漏",@"合伙人"];
    NSMutableArray* childVCs = [NSMutableArray array];
    [childVCs addObject:[[ConClubViewController alloc]init]];
    [childVCs addObject:[[ConDynamicViewController alloc]init]];
    [childVCs addObject:[[ConYueViewController alloc]init]];
    [childVCs addObject:[[ConPickViewController alloc]init]];
    [childVCs addObject:[[ConAdderViewController alloc]init]];
    [self.segmentBarVC setupWithItems:items childVCs:childVCs];
    [self.segmentBarVC.segmentBar updateViewWithConfig:^(TGSegmentConfig *config) {
        config.selectedColor([UIColor whiteColor])
        .normalColor(RGBColorOne(204))
        .selectedFont([UIFont boldSystemFontOfSize:18])//选中字体大于其他正常标签的字体的情况下，根据情况稍微调大margin（默认8），以免选中的字体变大后挡住其他正常标签的内容
        .normalFont([UIFont systemFontOfSize:16])
        .indicateExtraW(8)
        .indicateH(0)
        .indicateColor([UIColor clearColor])
        .showMore(NO)//是否显示更多面板
        .circleScroll(NO)//是否循环滚动，第0个再向前，那么到最后一个;最后一个向后，那么到第0个
        .moreCellBGColor([[UIColor grayColor] colorWithAlphaComponent:0.3])
        .moreBGColor([UIColor clearColor])
        .moreCellFont([UIFont systemFontOfSize:13])
        .moreCellTextColor(NavTinColor)
        .moreCellMinH(30)
        .showMoreBtnlineView(YES)
        .moreBtnlineViewColor([UIColor lightTextColor])
        .moreBtnTitleFont([UIFont systemFontOfSize:13])
        .moreBtnTitleColor([UIColor lightTextColor])
        .margin(18)
        .barBGColor(NavTinColor)
        ;
    }];
}
- (void)setLocation
{
    _locService = [[BMKLocationService alloc]init];
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_locService stopUserLocationService];
    if ([SZLAccountHelper isAlreadyLogin]) {
        [self upLoadGPS:userLocation.location.coordinate];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    _locService.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    //启动LocationService
    [_locService startUserLocationService];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _locService.delegate = nil; // 不用时，置nil
}
- (void)setNav
{
//    self.naviBackView = self.navigationController.navigationBar.subviews.firstObject;
//    self.naviBackView.alpha = 0.0;
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
    //去掉导航条横线
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
#pragma mark --------------------------------------------------------
    UIButton *messageBtn = [[UIButton alloc]init];
    messageBtn.frame = CGRectMake(0, 0, 30,30);
    [messageBtn setImage:GetImage(@"add_white") forState:UIControlStateNormal];
    [messageBtn addTarget:self action:@selector(rightItemClick) forControlEvents:UIControlEventTouchUpInside];
    messageBtn.tag = 1;
    self.messageBtn = messageBtn;
//    [messageBtn sizeToFit];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -10;
    
    self.navigationItem.rightBarButtonItems = @[negativeSpacer,[[UIBarButtonItem alloc]initWithCustomView:messageBtn]];
}
- (void)rightItemClick
{
    if ([SZLAccountHelper shouldLogin]) return;
    CoverView *cover = [[CoverView alloc]initWithFrame:[UIScreen mainScreen].bounds Titles:@[@"扫一扫",@"消息",@"分享"] backStart:47];
    __WEAK
    cover.btnBlock = ^(NSInteger index){
        if (index == 0) {
            [self getDeviceIsAvaliable];
        }else if (index == 1) {
            SZLMessageListViewController *messageVc = [[SZLMessageListViewController alloc]init];
            [weakSelf.navigationController pushViewController:messageVc animated:YES];
        }else {
            [self getShareContent];
        }
    };
    [cover showSelectView];
}
#pragma mark ----------------------tableviewDelegate滑动控制----------------
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
////    self.naviBackView.alpha = (scrollView.contentOffset.y+KBannerH)/(KBannerH-64);
//    if (-scrollView.contentOffset.y+1 >= self.searctBarmaxY) {//5s上有0.5的误差 +1修正一下
//        [self.navigationController setNavigationBarHidden:YES animated:YES];
//    }else{
//        [self.navigationController setNavigationBarHidden:NO animated:YES];
//    }
//}
- (void)upLoadGPS:(CLLocationCoordinate2D)coor2d
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"longitude"] = @(coor2d.longitude);
    parame[@"latitude"] = @(coor2d.latitude);
    [HomeNetService upLoadGPSWithParame:parame response:^(BOOL success, NSString *msg) {
        if (success) {
            NSLog(@"上传坐标成功");
        }else {
            NSLog(@"%@",msg);
        }
    }];
}
- (void)getShareContent
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showWaiter];
    [PersonNetWork getShareContentWithParame:parame response:^(BOOL success, NSString *msg, ShareContentModel *model) {
        [self hideWaiter];
        if (success) {
            [ShareTool share:model];
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
//检查相机可用以及权限
- (void)getDeviceIsAvaliable
{
    __WEAK
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        ConQrCodeScannerController *codeVc = [[ConQrCodeScannerController alloc]init];
                        [weakSelf.navigationController pushViewController:codeVc animated:YES];
                    });
                    NSLog(@"用户第一次同意了访问相机权限");
                } else {
                    NSLog(@"用户第一次拒绝了访问相机权限");
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
            ConQrCodeScannerController *codeVc = [[ConQrCodeScannerController alloc]init];
            [weakSelf.navigationController pushViewController:codeVc animated:YES];
        } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"⚠️ 警告" message:@"请去-> [设置 - 隐私 - 相机 - 玩转地球] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertC addAction:alertA];
            [weakSelf presentViewController:alertC animated:YES completion:nil];
            
        } else if (status == AVAuthorizationStatusRestricted) {
            NSLog(@"因为系统原因, 无法访问相册");
        }
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertC addAction:alertA];
        [weakSelf presentViewController:alertC animated:YES completion:nil];
    }
}

#pragma mark --------------------new------------------------
- (TGSementBarVC *)segmentBarVC
{
    if (!_segmentBarVC) {
        _segmentBarVC = [[TGSementBarVC alloc] init];
    }
    return _segmentBarVC;
}


@end
